package fr.umlv.projet.android.saisi.other;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import android.content.Context;
import android.os.Environment;
import android.util.AttributeSet;
import android.widget.EditText;
import fr.umlv.projet.android.saisi.SaveResponse;

public class TakeString extends EditText implements SaveResponse {

	public TakeString(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public TakeString(Context context) {
		super(context);
	}

	private String destFile;
	private String pathFile;
	private static final String basePath = Environment.getExternalStorageDirectory().getAbsolutePath();

	@Override
	public boolean save() {
		File dest = new File(pathFile + destFile + ".txt");
		if (!dest.getParentFile().exists()) {
			dest.getParentFile().mkdirs();
		}
		try {
			if (!dest.exists())
				dest.createNewFile();
			FileWriter fw = new FileWriter(dest.getAbsoluteFile());
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(getText().toString());
			bw.close();
		} catch (IOException io) {
			return false;
		}
		return true;
	}

	@Override
	public void setDestFile(String desFile) {
		this.destFile = desFile;
	}

	@Override
	public void setPathFile(String pathFile) {
		if (!pathFile.endsWith("/"))
			pathFile += "/";
		this.pathFile = basePath + pathFile;
	}

}
